********************************************************************
* This file generates the estimates reported in Table 4, Column 2. *
********************************************************************

*************************
* 0 Set path to files *
*************************
clear all
capture log close
set more off
set trace off
cd $main_directory

//Set predetermined values:
sca scale=10

//Load the data and the commands used in the estimation of the spatial demand model
use "Data_Belgium\Generated_data\baseline_demand_dataset.dta"
qui do "Command_files\spatial_demand_Q1.do"

//Calculate the total demand on the market
qui su Q1 if common==1
sca sumQ1=r(sum)
sca di sumQ1

//Calculate the total population on the market
bysort market_ID:  gen dup_market = cond(_N==1,0,_n)
qui su population if dup_market<2
sca sumPopulation=r(sum)
sca di sumPopulation

//Calculate total potential demand per capita as 10 times larger than the current value.
scalar gamma=10*sumQ1/sumPopulation
sca di gamma

//Calculate the market size (i.e. number of possible transactions)
gen market_size=gamma*population

//Define the product for which demand will be estimated (in this case realestate transactions).
gen firm_demand=Q1 
drop if firm_demand==.
drop if firm_demand<=0
gen log_demand = log(firm_demand)

//Generate a unique numeric identifier for the market.
sort market_ID
egen market_ID_num = group(market_ID)

// Controls
global controls_utility distance lnNotPerOff start_not LDE Perc_Young Perc_Elderly log_income popdens
global controls_total firm_ID firm_demand market_ID_num market_size $controls_utility

//Estimate the demand for realestate transactions: this is column 2 of Table 4.
spatialdemand_logQ1 $controls_total
//Store the estimates for later use.
parmest,  saving("Estimates\spatial_demand_Q1", replace)
mat list e(b)
est store spatial_Q1
mata: betas_Q1=st_matrix("e(b)")'
mata: betas_Q1
mata: mata matsave "Estimates/betas_Q1" betas_Q1, replace
nlcom 1/(1+exp(-_b[nest]))
